package com.zk.config.web.op;

import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.github.zkclient.ZkClient;
import com.zk.config.web.model.User;
import com.zk.config.web.util.AuthUtils;

public class ClientCacheManager {
	private static MyZkClient client = null;
	public static final String PRE = "zk-client-";

	public static MyZkClient getClient(String cxnString) {
		HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
		String key = PRE + cxnString;
		Object obj = session.getAttribute(key);
		if(obj == null) {
			client = new MyZkClient(cxnString, 10000);
			// 目录不存在则创建
			if(!client.exists("/")) {
				int index = cxnString.indexOf("/");
				if(index > 0) {
					client.close();
					client = null;
					String root = cxnString.substring(0, index);
					String cxnRoot = cxnString.substring(index);
					ZkClient clientRoot = new ZkClient(root, 10000);
					clientRoot.createPersistent(cxnRoot, true);
					clientRoot.close();
					client = new MyZkClient(cxnString, 10000);
				}
			}
			
			String userName = (String)session.getAttribute(AuthUtils.ZK_USER);
			if (userName != null) {
				User user = AuthUtils.userInfo.get(userName);
				if(user != null) {
					client.getZooKeeper().addAuthInfo("digest", (userName+":"+user.getPassword()).getBytes());
				}
			}
			session.setAttribute(key, client);
		} else {
			client = (MyZkClient) obj;
		}
		return client;
	}
}
